<script setup lang="ts">
import { ref } from 'vue'
import { getRandomImage } from '@/api/auth'
import { useThemeStore } from '@/store/theme'

// Props
interface Props {
  // 可选的初始checkKey
  initialCheckKey?: number
  // 验证码图片的宽度
  width?: string
  // 验证码图片的高度
  height?: string
  // 是否禁用
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  initialCheckKey: 0,
  width: 'w-28',
  height: 'h-10',
  disabled: false,
})

const emit = defineEmits<Emits>()

// Emits
interface Emits {
  (e: 'update:checkKey', checkKey: number): void
  (e: 'load', imageSrc: string, checkKey: number): void
}

// 响应式数据
const captchaImage = ref('')
const checkKey = ref(props.initialCheckKey)
const loading = ref(false)

// 主题store
const themeStore = useThemeStore()

// 加载验证码图片
async function loadCaptchaImage() {
  if (props.disabled)
    return

  try {
    loading.value = true
    // 生成当前时间戳作为key
    const timestamp = Date.now()
    const res = await getRandomImage(timestamp.toString())
    if (res.code === -1) {
      throw new Error('获取验证码失败')
    }
    captchaImage.value = res.data
    checkKey.value = timestamp

    // 发送事件更新父组件
    emit('update:checkKey', timestamp)
    emit('load', res.data, timestamp)
  }
  catch (error) {
    console.error('加载验证码失败:', error)
  }
  finally {
    loading.value = false
  }
}

// 处理点击刷新
function handleRefresh() {
  if (!props.disabled && !loading.value) {
    loadCaptchaImage()
  }
}

// 暴露方法给父组件
defineExpose({
  reload: loadCaptchaImage,
  getCheckKey: () => checkKey.value,
  getImageSrc: () => captchaImage.value,
})

// 组件挂载时加载验证码
onLoad(() => {
  loadCaptchaImage()
})
</script>

<template>
  <view class="relative">
    <image
      :src="captchaImage"
      class="rounded-lg object-cover transition-transform duration-200 active:scale-95" :class="[props.width, props.height, themeStore.theme === 'light' ? 'bg-gray-100' : 'bg-gray-800']"
      mode="scaleToFill"
      :style="{ opacity: loading || disabled ? 0.6 : 1 }"
      @click="handleRefresh"
    />
    <!-- 加载中状态指示器 -->
    <view v-if="loading" class="absolute inset-0 flex items-center justify-center">
      <view class="h-4 w-4 animate-spin border-2 border-current border-r-transparent rounded-full" :class="themeStore.theme === 'light' ? 'border-gray-600' : 'border-white'" />
    </view>
    <!-- 禁用状态遮罩 -->
    <view v-if="disabled" class="absolute inset-0 rounded-lg" />
  </view>
</template>
